package com.ixuestar.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONObject;
import com.ixuestar.dao.EasyPrintingMapper;
import com.ixuestar.entity.YxWxuser;
import com.ixuestar.service.EasyPrintingService;
import com.ixuestar.wxutil.GetwxOpenId;

public class EasyPrintingServiceImpl implements EasyPrintingService {

	@Autowired
	private EasyPrintingMapper easyPrintingMapper;
	
	@Override
	public JSONObject getWxuserInfo(JSONObject jsonObject) {
		// TODO Auto-generated method stub
		int code = 0;
		JSONObject yxuserObject = new JSONObject();
		try {
			String wxIv = jsonObject.getString("wxIv");
			String openId = jsonObject.getString("openId");
			String wxSessionKey = jsonObject.getString("wxSessionKey");
			String encryptedData = jsonObject.getString("encryptedData");
			//执行接口
			final JSONObject wxTelephone = GetwxOpenId.getWxTelephone(encryptedData, wxSessionKey, wxIv);
			//创建用户信息
			if (!wxTelephone.isEmpty()) {
				String phoneNumber = wxTelephone.getString("phoneNumber");
				//首先判断是否已经存在此用户信息
				Map<String, Object> hashMap = new HashMap<>();
				hashMap.put("lineKey", "ywOpenId");
				hashMap.put("lineValue", openId);
				YxWxuser yxWxuser = easyPrintingMapper.getYxWxuser(hashMap);
				//如果不存在 则写入
				if (yxWxuser==null) {
					YxWxuser yxWxuser2 = new YxWxuser();
					//创建ywId
					String ywId = "yw" + new Date().getTime() + (int)(Math.random()*10);
					//创建时间
					String ywCreatetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
					yxWxuser2.setYwId(ywId);
					yxWxuser2.setYwOpenId(openId);
					yxWxuser2.setYwImgUrl("");
					yxWxuser2.setYwType("0");
					yxWxuser2.setYwTelephone(phoneNumber);
					yxWxuser2.setYwCreatetime(ywCreatetime);
					yxWxuser2.setIxssId(null);
					easyPrintingMapper.writeYxWxuser(yxWxuser2);
					yxuserObject.putAll((JSONObject)JSONObject.toJSON(yxWxuser2));
				}else {
					yxuserObject.putAll((JSONObject)JSONObject.toJSON(yxWxuser));
				}
			}else {
				code = 1;
			}
			//返回
			jsonObject.put("code", code);
			jsonObject.put("yxWxuser", yxuserObject);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return jsonObject;
	}
}
